<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>学员注册</h2>
          <p>创建您的学员账号</p>
        </div>
      </template>

      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="80px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="registerForm.realName" placeholder="请输入真实姓名">
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号码">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="loading" class="register-button">
            注册
          </el-button>
          <el-button @click="$router.push('/login')" class="login-button">
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
// 需要引入图标
import { User, Lock, UserFilled, Phone } from '@element-plus/icons-vue'

export default {
  name: 'Register',
  components: { User, Lock, UserFilled, Phone }, // 注册图标
  setup() {
    const router = useRouter()
    const registerFormRef = ref(null)
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      realName: '',
      phone: '',
      userType: 'student'
    })
    const loading = ref(false)

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (registerForm.confirmPassword !== '') {
          if (registerFormRef.value) {
            registerFormRef.value.validateField('confirmPassword')
          }
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, validator: validatePass, trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    }

    const handleRegister = async () => {
      if (!registerFormRef.value) return;
      
      registerFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const postData = {
              username: registerForm.username,
              password: registerForm.password,
              realName: registerForm.realName,
              phone: registerForm.phone,
              userType: registerForm.userType
            }
            
            const response = await axios.post('/api/register', postData)
            
            if (response.data.code === 200) {
              ElMessage.success('注册成功')
              router.push('/login')
            } else {
              ElMessage.error(response.data.message)
            }
          } catch (error) {
            console.error('注册失败:', error);
            ElMessage.error('注册失败，请稍后重试')
          } finally {
            loading.value = false
          }
        } else {
          ElMessage.error('请填写完整的注册信息');
          return false;
        }
      });
    }

    return {
      registerForm,
      loading,
      rules,
      handleRegister,
      registerFormRef
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  padding: 20px;
}

.register-card {
  width: 500px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.card-header p {
  margin: 10px 0 0;
  color: #666;
}

.register-button {
  width: 100%;
  margin-bottom: 10px;
}

.login-button {
  width: 100%;
}
</style>